package com.amit.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(name="register",urlPatterns={"/register.jlc"})
public class RegisterServlet extends HttpServlet 
{

	UserService us=null;
	@Override
	public void init(ServletConfig config) throws ServletException {
		
		
		us=new UserService();
		
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		
		//1.collect the data
		
		
		String fn=request.getParameter("fname");
		String em=request.getParameter("email");
		String ph=request.getParameter("phone");
		String un=request.getParameter("username");
		String pw=request.getParameter("password");
		
		int uid=us.getNextUserId();
		
		long ph1=Long.parseLong(ph);
		
		UserTO uto=new UserTO(uid, fn, em, ph1, un, pw);
		
		int x=us.registerUser(uto);
		
		HttpSession session=request.getSession();
		String  result=" ";
		
		if(x==1)
		{
			session.setAttribute("UN",un);
			result="home.jsp";
			String sub="Registration success";
			String body="<h1>Hi"+fn+"Your Registration has been completed Successfully</h1>";
			MailService.sendMail(em,sub,body);
		}
		else
		{
			String msg="Registraion Failed-Try Again";
			request.setAttribute("MSG", msg);
			result="register.jsp";
		}
		
		RequestDispatcher rd=request.getRequestDispatcher(result);
		rd.forward(request, response);
		
	
		
	}
	
}
